<template>
	<view class="select-city-wrap background_white">
		<view class="select-city">
			<view class="index-bg-view">
				<view class="index" @touchmove="touchMoveIndex">
					<view class="index-item" @click="scrollTo('#')">#</view>
					<view class="index-item" v-for="item in citys" :key="item.letter" @click="scrollTo(item.letter)">
						{{ item.letter }}
					</view>
				</view>
			</view>
			<scroll-view :scroll-into-view="scrollIntoId" @scroll="scrollChange" :scroll-y="true"
				:scroll-with-animation="isAnimation" :style="{ height: windowHeight }">
				<view class="content">
					<!-- 定位城市 -->
					<view class="flex_col" style="align-items: flex-start;">
						<view style="font-size: 28rpx;color: #170E0F;">定位城市</view>
						<view class="flex_row center" @click="click_location_city"
							style="margin-top: 24rpx;width: 156rpx;background-color: #F5F5F5;height: 60rpx;border-radius: 8rpx;">
							<text class="iconfont icon_location_grey" style="font-size: 24rpx;color: black;" />
							<view style="font-size: 26rpx;color: black;margin-left: 6rpx;">{{location_city}}</view>
						</view>
					</view>

					<!-- 热门城市 -->
					<view class="flex_col" style="align-items: flex-start;margin-top: 48rpx;">
						<view style="font-size: 28rpx;color: #170E0F;">热门城市</view>
						<view class="flex_row wrap">
							<view v-for="item,index in hotCitys" :key="index">
								<view @click="select_hot(item,index)"
									:class="selected_hot_index == index ? 'hot_selected' : 'hot_unselected' ">{{item.city_name}}
								</view>
							</view>
						</view>
					</view>

					<!-- 城市列表 -->
					<view class="section" :id="item.letter" v-for="item in citys" :key="item.letter"
						style="margin-top: 40rpx;">
						<view class="letter">{{ item.letter }}</view>
						<view class="city-list">
							<view class="flex_col">
								<view class="city-item" :class="{ active: current === city }"
									v-for="(city, itemIndex) in item.list" :key="itemIndex" @click="onSelect(city)">
									{{ city.name }}
								</view>
							</view>
						</view>
					</view>
				</view>
			</scroll-view>
		</view>
	</view>
</template>
<script>
	import {
		request
	} from "../api/request.js"
	import store from '../utils/store.js'
	export default {
		name: "select_city",
		props: {
			value: {
				type: String,
				default: ''
			},
			locationValue: {
				type: String,
				default: ''
			}
		},
		computed:{
			location_city(){
				return store.state.city.name
			},
		},
		data() {
			return {
				hotCitys:[],
				citys: [{
					"letter": "A",
					"list": []
				}, {
					"letter": "B",
					"list": []
				}, {
					"letter": "C",
					"list": []
				}, {
					"letter": "D",
					"list": []
				}, {
					"letter": "E",
					"list": []
				}, {
					"letter": "F",
					"list": []
				}, {
					"letter": "G",
					"list": []
				}, {
					"letter": "H",
					"list": []
				}, {
					"letter": "I",
					"list": []
				}, {
					"letter": "J",
					"list": []
				}, {
					"letter": "K",
					"list": []
				}, {
					"letter": "L",
					"list": []
				}, {
					"letter": "M",
					"list": []
				}, {
					"letter": "N",
					"list": []
				}, {
					"letter": "O",
					"list": []
				}, {
					"letter": "P",
					"list": []
				}, {
					"letter": "Q",
					"list": []
				}, {
					"letter": "R",
					"list": []
				}, {
					"letter": "S",
					"list": []
				}, {
					"letter": "T",
					"list": []
				}, {
					"letter": "U",
					"list": []
				}, {
					"letter": "V",
					"list": []
				}, {
					"letter": "W",
					"list": []
				}, {
					"letter": "X",
					"list": []
				}, {
					"letter": "Y",
					"list": []
				}, {
					"letter": "Z",
					"list": []
				}, ],
				all_cities: [],
				windowHeight: '',
				scrollIntoId: 'F',
				current: this.value,
				itemBounds: {},
				marginTopHeight: 0,
				isAnimation: true,
				query: null,
				selected_hot_index: 0, // 选择的热门城市index
				all_city_code: []
			};
		},
		mounted() {
			this.getSystemInfo();
			this.getCitys()
			this.getHotCity()
		},
		created() {
			let that = this;
			uni.$on('upadteLoaction', function(city) {
				that.current = city;
				console.log(city);
			});
		},
		beforeDestroy() {
			uni.$off(['upadteLoaction']);
		},
		methods: {
			click_location_city(){
				this.location_city
			},
			getHotCity() {
				request({
					url: this.Api.GetHotCity,
					method: "GET",
					data: {
						
					},
					success: (response) => {
						console.log("热门城市")
						console.log(response.data.dataset.data)
						this.hotCitys = response.data.dataset.data
					},
					fail: () => {
						console.log("fail")
					},
					complete: () => {
						console.log("complete")
					},
				})
			},
			//获取所有的城市
			getCitys() {
				var citys = this.LocalStorage.get(this.constants.CITY_INFO)
				if (citys) {
					console.log("缓存")
					this.process_city(citys)
				} else {
					console.log("网络")
					request({
						url: this.Api.GetCityList,
						method: "GET",
						data: {},
						success: (response) => {
							this.LocalStorage.set(this.constants.CITY_INFO, response.data.dataset.data)
							this.process_city(response.data.dataset.data)
						},
						fail: () => {
							console.log("fail")
						},
						complete: () => {
							console.log("complete")
						},
					})
				}
			},
			//处理城市信息
			process_city(response) {
				// console.log(response)
				let provinces = Object.keys(response.provincesData)
				// console.log(provinces)
				let cities = Object.keys(response.citiesData).filter(e => e.endsWith("0000")) //移除省份
				// console.log(cities)
				// console.log(this.get_city_name("120100"))
				cities.forEach(item => {

					this.all_cities = this.all_cities.concat(Object.values(response.citiesData[item]))
				})
				this.all_cities.sort((a, b) => {
					return a.alpha.charCodeAt(0) - b.alpha.charCodeAt(0)
				})

				this.citys.forEach(city => {
					this.all_cities.forEach(c => {
						if (city.letter == c.alpha) {
							city.list.push(c)
						}
					})
				})

				for (let key of Object.keys(response.citiesData)) {
					var item = response.citiesData[key]
					if (key.endsWith("0000")) {
						// console.log(key)
						// console.log(item)
						this.all_city_code.push(item)
					}
				}
				// console.log((this.get_city_code("北京市")))
			},
			get_city_code(name) {
				var result = ""
				this.all_city_code.forEach(a => {
					Object.values(a).forEach((b) => {
						if (b.name == name) {
							let codes = Object.getOwnPropertyNames(a)
							if (codes.length == 2) {
								result = codes[0]
								// return codes[0]
							} else {
								codes.forEach((i) => {
									if (a[i].name == name) {
										result = i
										// return i
									}
								})
							}
						}
					})
				})
				return result
			},
			//根据code获取cityName
			get_city_name(code) {
				return this.all_cities[code]
			},
			select_hot(item, index) {
				this.selected_hot_index = index
			},
			scrollChange: function(e) {},
			// 获取导航栏的高度
			getItemHeight: function() {
				let that = this;
				// this.query = uni.createSelectorQuery().in(this);
				let query = uni.createSelectorQuery();
				// #ifndef MP-ALIPAY || MP-DINGTALK
				query = query.in(this) // 支付宝小程序不支持in(this),而字节跳动小程序必须写in(this), 否则都取不到值
				// #endif
				
				query.select('.index-item')
					.boundingClientRect(data => {
						let itemW = data.width;
						let itemH = data.height;
						that.itemBounds = {
							width: itemW,
							height: itemH
						};
					})
					.exec();
				query.select('.index')
					.boundingClientRect(data => {
						// console.log(data);
						// console.log(this.windowHeight);
						// console.log(data.height);
						this.marginTopHeight = (parseInt(this.windowHeight) - parseInt(data.height)) / 2;
						// console.log(this.marginTopHeight);
					})
					.exec();
				query.select('.letter')
					.boundingClientRect(data => {
						// console.log(data);

					})
					.exec();
			},
			getSystemInfo() {
				uni.getSystemInfo().then(res => {
					let [error, data] = res;
					this.windowHeight = `${data.windowHeight}px`;
					this.getItemHeight();
				});
			},

			scrollTo(letter) {
				console.log(letter);
				this.isAnimation = false;
				this.scrollIntoId = letter === '#' ? 'current' : letter;
			},
			onSelect(city) {
				// debugger
				console.log(this.all_cities)
				this.all_cities.forEach(city => {
					// if(city.name )
				})
				console.log(city);
				this.current = city;
				this.$emit('input', city);
				this.$emit('on-select', city);
			},

			touchMoveIndex: function(e) {
				let info = e.changedTouches[0];
				// console.log('开始移动点：' + info.pageY);
				let itemY = info.pageY - this.marginTopHeight;
				var count = Math.ceil(itemY / this.itemBounds.height);
				if (count == 1) {
					this.isAnimation = true;
					this.scrollIntoId = 'current';
					return;
				}
				// console.log(count);
				if (count > 23) {
					return
				}
				if (count - 1 > 0) {
					count = count - 1;
				}
				let item = this.citys[count - 1];
				if (this.scrollIntoId == item.letter) {
					return;
				}
				// console.log(item.letter);
				this.isAnimation = true;
				this.scrollIntoId = item.letter === '#' ? 'current' : item.letter;
			}
		}
	};
</script>

<style lang="scss" scoped>
	.hot_selected {
		margin-top: 12rpx;
		margin-right: 12rpx;
		width: 156rpx;
		height: 60rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		background-color: #FED5E2;
		font-size: 26rpx;
		color: #FC014E;
		border-radius: 8rpx;
	}

	.hot_unselected {
		margin-top: 12rpx;
		margin-right: 12rpx;
		width: 156rpx;
		height: 60rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		background-color: #F5F5F5;
		font-size: 26rpx;
		color: #170E0F;
		border-radius: 8rpx;
	}

	.select-city-wrap {
		position: relative;
		padding: 0 30upx;
		// background-color: $green;
	}

	.index-item {
		width: 60upx;
		height: 42upx;
		font-size: 20rpx;
		color: #999999;
		line-height: 42upx;
		text-align: center;
	}

	.select-city {
		.index-bg-view {
			position: absolute;
			right: 10upx;
			z-index: 999;

			height: 100%;
			width: 60upx;
			display: flex;
			justify-content: center;
			align-items: center;
		}

		.index {
			// position: absolute;
			// right: 10upx;
			// top: 140upx;
			// z-index: 999;
			color: rgba(255, 255, 255, 0.5);
			font-size: 32upx;
		}

		.section {
			margin-bottom: 19upx;

			.city-title {
				color: black;
				font-size: 28upx;
				margin-bottom: 28upx;
				margin-top: 30rpx;
			}

			.letter {
				width: 44upx;
				height: 44upx;
				color: black;
				font-weight: bold;
				// border-radius: 100%;
				// background-color: #2f9bfe;
				font-size: 28upx;
				line-height: 44upx;
				text-align: center;
				margin-bottom: 30upx;
			}

			.city-list {
				// display: flex;
				// flex-wrap: wrap;

				.city-item {
					height: 80rpx;
					border-bottom: solid 1rpx #F3F3F3;
					// display: flex;
					// flex-direction: row;
					margin-right: 20upx;
					margin-bottom: 20upx;
					line-height: 64upx;
					// border: 1px solid #dcdcdc;
					// border-radius: 8upx;
					color: black;
					font-size: 28upx;
					background-color: rgba(255, 255, 255, 0.1);

					// 选中状态
					// &.active {
					//     background-color: black;
					//     // border-color: #2f9bfe;
					//     color: black;
					// }
				}
			}
		}
	}
</style>
